//
//  XXTGSearchAreaView.m
//  XiuXiuTuanGou
//
//  Created by 王克博 on 2018/8/10.
//  Copyright © 2018年 XiuXiuTuanGou. All rights reserved.
//

#import "XXTGSearchAreaView.h"
#import "XXTGChooseAddressTableViewCell.h"
//#import "XXTGNetWorking+Mine.h"


#define gap 0.3
#define cellH [self fitSize:48]

@interface XXTGSearchAreaView() <UITableViewDelegate, UITableViewDataSource, AMapSearchDelegate>

@property (copy, nonatomic) NSString *city;
@property (copy, nonatomic) NSString *keyword;

@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic, strong) UITableViewCell *aimsCell;

@end

@implementation XXTGSearchAreaView

- (void)dismissView{
    self.tapGestureBlock();
}

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.tableView.frame = frame;
        
        self.backgroundColor = RGBA(0, 0, 0, 0.5);
        
        CAShapeLayer *line = [CAShapeLayer layer];
        line.fillColor = KWhiteColor.CGColor;
        UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, KScreenWidth, gap)];
        line.path = path.CGPath;
        
        [self.layer addSublayer:line];
        
        [self createUI];
        
        [self initSearch];
        
       // [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissView)]];
    }
    return self;
}


#pragma mark - 搜索提示
- (void)initSearch{
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
}


- (void)keywordsSearchWithKeywords:(NSString *)keywords{
    
    AMapInputTipsSearchRequest *tipsRequest = [[AMapInputTipsSearchRequest alloc] init];
    tipsRequest.keywords = keywords;
    [self.search AMapInputTipsSearch:tipsRequest];
}

#pragma mark - 搜索提示回调函数

-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest*)request response:(AMapInputTipsSearchResponse *)response
{
    
    if (response.tips.count >0) {
        
        _locations = [response.tips mutableCopy];
    }else if (response.tips.count == 0){
        
        [_locations removeAllObjects];
    }
    
    kWeakSelf(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [weakself.tableView reloadData];;
    });

}


- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    self.tableView.frame = CGRectMake(0, gap, frame.size.width, self.size.height - gap);
    self.backView.frame = CGRectMake(0, gap, frame.size.width, frame.size.height - gap);
}


- (void)createUI
{
    [self addSubview:self.backView];
    [self addSubview:self.tableView];
//    [self setupFooterRefreshs];
    [self.tableView registerClass:[XXTGChooseAddressTableViewCell class] forCellReuseIdentifier:@"XXTGChooseAddressTableViewCell"];
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture)];
    [self.backView addGestureRecognizer:tapGesture];
}

- (void)tapGesture
{
    if (self.tapGestureBlock) {
        self.tapGestureBlock();
    }
}

//tableview开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//    if (self.beginDraggingBlock) {
//        self.beginDraggingBlock();
//    }
}

//更改city或者关键字 外部调用
//- (void)changeKeywordWithCity:(NSString *)city keyword:(NSString *)keyword
//{
//    [self.tableView scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
//    self.city = city;
//    self.keyword = keyword;
//    self.page = 1;
//    
//    NSString * lng;
//    NSString * lat;
//    if ([kUserDefaults objectForKey:kLocationLongitudeKey]) {
//        lng = [kUserDefaults objectForKey:kLocationLongitudeKey];
//    }else {
//        lng = @"";
//    }
//    if ([kUserDefaults objectForKey:kLocationLatitudeKey]) {
//        lat = [kUserDefaults objectForKey:kLocationLatitudeKey];
//    }else {
//        lat = @"";
//    }
//    XXTGNetWorking *manager = [XXTGNetWorking sharedInstance];
//    __weak typeof(self) weakself = self;
//    [manager getSearchListRegion:city keyword:keyword longitude:lng latitude:lat page:self.page CallBack:^(BOOL isSucessed, id outParam, NSString *eMsg) {
//        [weakself.tableView.mj_footer endRefreshing];
//        if (weakself.areaArray.count > 0) {
//            [weakself.areaArray removeAllObjects];
//        }
//        if (isSucessed == YES && [outParam[@"code"] integerValue] == 2000) {
//            NSArray * array = outParam[@"data"][@"tmpInfo"];
//            [weakself.areaArray addObjectsFromArray:array];
//        }
//        [weakself.tableView reloadData];
//    }];
//}

//- (void)getMoreData
//{
//    self.page++;
//    NSString * lng;
//    NSString * lat;
//    if ([kUserDefaults objectForKey:kLocationLongitudeKey]) {
//        lng = [kUserDefaults objectForKey:kLocationLongitudeKey];
//    }else {
//        lng = @"";
//    }
//    if ([kUserDefaults objectForKey:kLocationLatitudeKey]) {
//        lat = [kUserDefaults objectForKey:kLocationLatitudeKey];
//    }else {
//        lat = @"";
//    }
//    XXTGNetWorking *manager = [XXTGNetWorking sharedInstance];
//    __weak typeof(self) weakself = self;
//    [manager getSearchListRegion:self.city keyword:self.keyword longitude:lng latitude:lat page:self.page CallBack:^(BOOL isSucessed, id outParam, NSString *eMsg) {
//        [weakself.tableView.mj_footer endRefreshing];
//        if (isSucessed == YES && [ outParam[@"code"] integerValue] == 2000) {
//            NSArray *array = outParam[@"data"][@"tmpInfo"];
//            [weakself.areaArray addObjectsFromArray:array];
//        }
//        [weakself.tableView reloadData];
//    }];
//}

//MARK: - tableview delegate datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.locations.count == 0) {
        self.tableView.hidden = YES;
    }else {
        self.tableView.hidden = NO;
    }
    return  self.locations.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"];
    }
    
    if (indexPath.row == 0) {
        
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        self.aimsCell = cell;
        
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    
    cell.tintColor = mMainColor;
    cell.textLabel.textColor = UIColorFromRGB(0x333333);
    cell.detailTextLabel.textColor = UIColorFromRGB(0x999999);
    
    AMapTip *mapPOI = _locations[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@", mapPOI.name];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", mapPOI.address];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.aimsCell != nil) {
        self.aimsCell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    self.aimsCell = cell;
    
    if (indexPath.row < self.locations.count) {
                
        if (self.choosedCellBlock) {
            AMapTip *tip = self.locations[indexPath.row];
            self.choosedCellBlock(indexPath.row,tip);
        }
    }
}


- (void)clearTableViewData
{
    [_locations removeAllObjects];
    [self.tableView reloadData];
}

#pragma mark - setter and getter

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.backgroundColor = mBackgroudColor;
        _tableView.dataSource = self;
        _tableView.rowHeight = cellH;
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    }
    return _tableView;
}

- (UIView *)backView
{
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectZero];
        _backView.backgroundColor = [UIColor clearColor];
    }
    return _backView;
}


@end
